<?php
declare (strict_types=1);

namespace app\common\model;

use quick\admin\library\tools\CodeTools;
use think\Model;


/**
 * Class SystemUser
 *
 *
 * @property integer  $id              账号id
 * @property string   $username        账户名称
 * @property string   $nickname        昵称
 * @property string   $avatar          头像
 * @property string   $email           电子邮箱
 * @property string   $phone           手机号
 * @property string   $password        密码
 * @property string   $salt            密码盐
 * @property integer  $status          状态 1:启用, 0:禁用
 * @property string   $last_login_ip_at 最后一次登录ip
 * @property string   $create_ip_at    创建ip
 * @property integer  $login_num       登录次数
 * @property integer  $login_fail_num  失败次数
 * @property integer  $is_deleted      删除: 1已删除 0未删除
 * @property string   $login_at
 * @property string   $deleted_at      删除日期
 * @property string   $created_at      创建日期
 * @property string   $updated_at      更新日期
 * @property-read \app\common\model\SystemUserInfo $user_info
 * @package app\common\model
 */
class SystemUser extends BaseModel
{

    /** @var string h5平台标识 */
    const PLATFORM_H5 = 'mobile';

    /** @var string 微信平台公众号 */
    const PLATFORM_WECHAT = 'wechat';

    /** @var string 微信平台小程序 */
    const PLATFORM_WXAPP = 'wxapp';

    /** @var string 注册事件 */
    const  EVENT_REGISTER = "event_register";

    /** @var string 登录事件 */
    const  EVENT_LOGIN = "event_login";


    protected $name = 'system_user';


    /**
     * 验证规则
     * @return array
     */
    protected function rules(): array
    {
        return [
            'id' => 'integer',
            'username' => 'require|max:50',
            'nickname' => 'max:50',
            'avatar' => 'max:150',
            'email' => 'max:100',
            'phone' => 'max:15',
            'password' => 'max:32',
            'salt' => 'max:30',
            'status' => 'integer',
            'last_login_ip_at' => 'max:25',
            'create_ip_at' => 'max:25',
            'login_num' => 'integer',
            'login_fail_num' => 'integer',
            'is_deleted' => 'integer',
        ];
    }


    /**
     * @return array
     */
    protected function attrLabels(): array
    {
        return [
            'id' => '账号id',
            'username' => '账户名称',
            'nickname' => '昵称',
            'avatar' => '头像',
            'email' => '电子邮箱',
            'phone' => '手机号',
            'password' => '密码',
            'salt' => '密码盐',
            'status' => '状态 1',
            'last_login_ip_at' => '最后一次登录ip',
            'create_ip_at' => '创建ip',
            'login_num' => '登录次数',
            'login_fail_num' => '失败次数',
            'is_deleted' => '删除',
            'login_at' => 'login_at',
            'deleted_at' => '删除日期',
            'created_at' => '创建日期',
            'updated_at' => '更新日期',
        ];
    }

    /**
     * @param String $password
     * @param String $salt
     * @return String
     */
    public static function hashPassword(string $password, string $salt = ''): string
    {
        return md5(md5($password) . $salt);
    }



    /**
     * 用户详细信息
     *
     * @return \think\model\relation\HasOne
     */
    public function userInfo()
    {
        return $this->hasOne(SystemUserInfo::class, "user_id");
    }


    /**
     * @param string $username
     * @param array $data 账户插入数据
     * @param array $admin 管理员表插入数据
     * @param int $is_super_admin
     * @param int $type 1 超级管理员 2 员工
     * @param int $userId 绑定已有账户
     * @return SystemUser|array|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function createAdminUser(string $username = '', array $data = [], array $admin = [], int $type = 0,int $userId = 0)
    {

        if($userId){

            $adminModel = SystemAdminInfo::where([
                'user_id' => $userId,
                'plugin_name' => $admin['plugin_name'],
                'is_deleted' => 0,
            ])->find();
            if($adminModel){
                throw new \Exception('当前账户已经绑定管理员！');
            }

            $user = SystemUser::where([
                'id' =>  $userId,
                'is_deleted' => 0,
            ])->find();
            if (!$user) {
                throw new \Exception('账户不存在');
            }

        }else{

            if(empty($username)){
                throw new \Exception('账户名称不能为空');
            }
            $user = SystemUser::where([
                'username' =>  $username,
                'is_deleted' => 0,
            ])->find();
            if ($user) {
                throw new \Exception('账户名已被占用');
            }


            $user = new SystemUser();
            $user->username = $username;
            $user->nickname = $data['nickname'] ?? $username;
            $user->phone = $data['phone'] ?? '';
            $user->email = $data['email'] ?? '';
            $user->avatar = $data['avatar'] ?? '';
            $user->status = 1;

            $password = $data['password'] ?? CodeTools::random(23,3);
            $salt = $data['salt'] ?? CodeTools::random(4,3);
            unset($data['username']);
            unset($data['password']);
            unset($data['salt']);

            $user->password = static::hashPassword($password, $salt);
            $user->salt = $salt;

            $res = $user->save($data);

            if (!$res) {
                throw new \Exception('添加失败');
            }


        }





        if (!empty($admin) && $admin['plugin_name']) {
            $adminInfo = new SystemAdminInfo();
            $res = $adminInfo->save(array_merge(['name' => $username, 'user_id' => $user->id], $admin));
            if (!$res) {
                throw new \Exception('添加失败');
            }
        }


        return $user;

    }


}
